define(['jsonpack', './../initial', './layer'], function(jsonpack) {
    var app = angular.module('App.home');
    app.factory('Project', ['$q', '$http', 'Layer',
        function($q, $http, Layer) {
            var prj = (function() {
                var prj = function() {
                    this.monitorPoints = [];
                    this.center = '';
                    this.name = '';
                    this.marker = null;
                    this.layers = [];
                    this.prjId = -1;
                    this.summary = null; //工程简介,应当是字符串数组,未赋值,选择工程后赋值.
                    this.active = false;
                    this.projectMapCenter = [];
                    this.statusList = null;
                    this.partitialStatusList = null;
                    this.matchSearch = true; //满足搜索要求,默认为是
                    this.mainStatusTimeList = null; //主要的工况时间以及工况描述数组{status,time}
                };
                prj.prjTypes = [{
                    typeCode: 'MetroMonitor',
                    typeName: '监护项目',
                    markerColor: 'red'
                }, {
                    typeCode: 'RoadTunnellMonitor',
                    typeName: '公路隧道',
                    markerColor: 'cadetblue'
                }, {
                    typeCode: 'CriticalSectionMonitor',
                    typeName: '长期沉降',
                    markerColor: 'purple'
                }];
                prj.curType = 'MetroMonitor';
                prj.prjs = [];
                prj.allPrjsByLine = null; //按线路分类的项目列表

                prj.getAllProjects = function(typeCode) {
                    typeCode = typeCode || 'MetroMonitor';
                    prj.curType = typeCode;
                    var defer = $q.defer();

                    if (!prj[typeCode + 'Projects']) {

                        $http({
                            url: '/projects/false/' + typeCode,
                            method: 'get'
                        }).success(function(data) {
                            prj.allPrjsByLine = data;
                            prj.prjs = [];

                            for (var i = 0; i < prj.allPrjsByLine.length; i++) {
                                prj.prjs = prj.prjs.concat(prj.allPrjsByLine[i].projects);
                            }

                            prj[typeCode + 'Projects'] = prj.prjs;
                            prj[typeCode + 'ProjectsByLine'] = data;
                            defer.resolve(prj[typeCode + 'Projects']);
                        });
                    } else {
                        prj.allPrjsByLine = prj[typeCode + 'ProjectsByLine'];
                        defer.resolve(prj[typeCode + 'Projects']);
                    }
                    return defer.promise;
                };

                prj.prototype.findAutoSurveyPoint = function(monitorType, location, deviceNo) {
                    var prj = this;
                    var ll = prj.findLocationPoints(monitorType, location);
                    var pts = ll.points.filter(function(item) {
                        return item.deviceNo === deviceNo.toString();
                    });
                    if (pts.length > 0) {
                        return pts[0];
                    } else {
                        return null;
                    }
                };

                prj.prototype.getMonitorItems = function() {
                    var prj = this;
                    var items = [];
                    for (var i = 0; i < prj.monitorPoints.length; i++) {
                        var lpts = prj.monitorPoints[i].locationPoints;
                        for (var j = 0; j < lpts.length; j++) {
                            items.push({
                                monitorType: prj.monitorPoints[i].monitorType,
                                location: lpts[j].location
                            });
                        }
                    }
                    return items;
                };
                //获取工程的主工况时间列表{status:string,time:dateStr}
                prj.prototype.getMainStatusTimeList = function() {
                    var defer = $q.defer();
                    var prjItem = this;
                    if (prjItem.mainStatusTimeList !== null) {
                        defer.resolve(prjItem.mainStatusTimeList);
                    }
                    $http({
                        url: '/mainStatusTimeList/' + prjItem.prjId,
                        method: 'get'
                    }).success((function(prjItem) {
                        return function(data) {
                            if (angular.isArray(data)) {
                                prjItem.mainStatusTimeList = data;
                            }
                            defer.resolve(data);
                        };
                    })(prjItem));
                    return defer.promise;
                };
                //给出监测类型和监测位置,返回监测点集
                prj.prototype.findLocationPoints = function(monitorType, location) {
                    var ll = null;
                    for (var i = 0; i < this.monitorPoints.length; i++) {
                        if (this.monitorPoints[i].monitorType === monitorType) {
                            var lpts = this.monitorPoints[i].locationPoints;
                            for (var j = 0; j < lpts.length; j++) {
                                if (lpts[j].location === location) {
                                    ll = lpts[j];
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    return ll;
                };


                prj.prototype.getRecentChanges = function(monitorType, location) {
                    var defer = $q.defer();
                    var prj = this;
                    var locationPts = this.findLocationPoints(monitorType, location);
                    locationPts.getRecentChanges(prj.prjId, monitorType).then(function(data) {
                        defer.resolve(locationPts.recentChanges);
                    });
                    return defer.promise;
                };

                prj.prototype.getRecent2Changes = function(monitorType, location, clickDates, fuzzy) {
                    fuzzy = fuzzy || "0";
                    var defer = $q.defer();
                    var prjItem = this;
                    var ll = prjItem.findLocationPoints(monitorType, location);
                    ll.getRecent2Changes(prjItem.prjId, monitorType, clickDates, null, fuzzy).then(function(data) {
                        defer.resolve(data);
                    });
                    return defer.promise;
                };

                prj.prototype.getProjectLayers = function() {
                    var defer = $q.defer();
                    var prjItem = this;
                    if (prjItem.layers.length > 0) {
                        defer.resolve(prjItem.layers);
                    } else {
                        $http({
                            url: '/getProjectLayers/' + prjItem.prjId,
                            method: 'get'
                        }).success(function(data) {
                            prjItem.layers = [];
                            data.forEach(function(item, index) {
                                var l = new Layer();
                                angular.extend(l, item);
                                l.layer = jsonpack.unpack(item.layer);
                                prjItem.layers.push(l);
                                if (l.title.toLowerCase() === 'ringnumber') {
                                    ringnumberIndex = index;
                                    prjItem.parseGeoInfoForEachPoint(l.layer); //赋值地理位置信息

                                }
                            });
                            prjItem.layers.splice(ringnumberIndex, 1); //删除ringnumber那一项
                            defer.resolve(prjItem.layers);
                        });
                    }
                    return defer.promise;
                };

                var findMachedPoint = function(pointsGeoJson, location, ringNumber) {
                    var matches = pointsGeoJson.features.filter(function(item) {
                        return item.properties.RingNumber.toString() === ringNumber;
                    });

                    if (matches.length === 0) {
                        return null;
                    } else if (matches.length === 1) {
                        return matches[0];
                    } else {
                        var finalMatches = matches.filter(function(item) {
                            return item.properties.Location === location;
                        });
                        return finalMatches[0] ? finalMatches[0] : null;
                    }
                };

                prj.prototype.parseGeoInfoForEachPoint = function(geoLayerData) {
                    var prjItem = this;
                    //find project map center
                    prjItem.projectMapCenter = L.geoJson(geoLayerData).getBounds().getCenter();
                    //parse geometry info to each monitor point
                    var pointsGeoJson = geoLayerData;
                    prjItem.monitorPoints.forEach(function(mPoints) {
                        mPoints.locationPoints.forEach(function(lpts) {
                            for (var t = 0; t < lpts.points.length; t++) {
                                var pt = lpts.points[t];
                                //服务器里没配置ringnumber的,默认为none
                                if (pt.ringNumber === 'none') {
                                    console.log(" location:%s name:%s ringnumber is null, config it.", pt.name, pt.ringNumber, lpts.location);
                                    lpts.isRingNumberConfig = false;
                                    break;
                                } else {
                                    var matchPt = findMachedPoint(pointsGeoJson, lpts.location, pt.ringNumber);
                                    try {
                                        pt.geometry = matchPt.geometry.coordinates;
                                    } catch (err) {
                                        console.log("fail on parse geo info at name:%s ring:%s location:%s", pt.name, pt.ringNumber, lpts.location);
                                        console.log("mainly because this ringnumber is not generated in ringnumber.json layer, verify it.");
                                        lpts.isRingNumberConfig = false;
                                        break;
                                    }
                                }

                            }
                        });
                    });
                };
                prj.prototype.getProjectSummary = function() {
                    var defer = $q.defer();
                    var prjItem = this;
                    if (prjItem.summary) {
                        defer.resolve(prjItem.summary);
                    } else {
                        $http({
                            url: '/getProjectSummary/' + prjItem.prjId,
                            method: 'get'
                        }).success((function(prjItem) {
                            return function(data) {
                                if (angular.isArray(data)) {
                                    prjItem.summary = data;
                                }
                                defer.resolve(data);
                            };
                        })(prjItem));
                    }
                    return defer.promise;
                };

                prj.prototype.getSinglePointRecentChanges = function(ptName, queryType, startTime, endTime) {
                    var prj = this;
                    queryType = queryType ? queryType : '10';
                    startTime = startTime ? startTime : '123';
                    endTime = endTime ? endTime : "123";
                    var deferred = $q.defer();
                    $http({
                        url: '/singlePointRecentChanges/' + prj.prjId + '/' + ptName + '/' + queryType + '/' + startTime + '/' + endTime,
                        method: 'get'
                    }).success(function(data) {
                        deferred.resolve(data);
                    });
                    return deferred.promise;
                };

                prj.prototype.getStatusList = function(partitial) {
                    var defer = $q.defer();
                    partitial = typeof(partitial) === 'undefined' ? true : partitial;
                    var partitialStr = partitial ? "partitialStatusList" : "statusList";
                    var prj = this;
                    if (prj[partitialStr]) {
                        defer.resolve(prj[partitialStr]);
                    } else {
                        $http({
                            url: '/projectStatus/' + prj.prjId.toString() + '/' + partitial.toString(),
                            method: 'get'
                        }).success(function(data) {
                            if (partitial === false) {
                                prj.partitialStatusList = prj.statusList = data;
                            } else {
                                prj[partitialStr] = data;
                            }
                            defer.resolve(data);
                        });
                    }
                    return defer.promise;
                }

                return prj;
            })();
            return prj;
        }
    ]);
});
